import threading
from lib import helper, resp
from lib.snowflake import Snowflake
from models.user_novel import UserNovel


class NovelService:

    local_data = threading.local()
    local_data.test_list = []

    def __init__(self) -> None:
        self.local_data.test_list = []
        pass

    def novel_list(self, story_name, page, limit):
        # self.local_data.test_list.append(Snowflake.unique_id())
        # print(self.local_data.test_list)
        c = UserNovel.table()
        if story_name != "":
            c.where("Name", "like", f"%{story_name}%")
        c.where("IsValid", 1)
        count = c.count()
        page_index = (page - 1) * limit
        list = c.take(limit).skip(page_index).get()
        return resp.ret_obj({"List": list, "Count": count})

    def novel_save(self, novel_id=0, data: dict = {}):
        t = UserNovel.table()
        info = t.where("NovelId", novel_id).first()
        if info:
            rs = t.update(helper.update_data_time(data))
        else:
            data["NovelId"] = Snowflake.unique_id()
            rs = UserNovel.table().insert(helper.add_data_time(data))
        if not rs:
            return resp.ret_failed()
        return resp.ret_obj()

    def novel_delete(self, novel_id):
        rs = UserNovel.table().where("NovelId", novel_id).update({"IsValid": 0})
        if rs:
            return resp.ret_obj()
        return resp.ret_failed()
